
(function () {
  new Vue({
    el: '#conflict',
    data() {
      return {
        data: '',
        getContractIndex: JSON.parse(window.sessionStorage.getItem('CHANGE_CONTRACT_INDEX')),
        mode: hlUrlUtil.GetQueryString('mode'),//变更模式
        id: hlUrlUtil.GetQueryString('id'),//合同ID
        detailflag: false,
        YSlist: [], //应收
        YTlist: [], //应退
        tzDate:'',
        conflictBills:[],
        chargeData:[],
        contratdata: [],
      isReceiveMatch: false,
      isRefundMatch: false,
      pics: [],
      filesUrl: [],
      memo: '',
      wCode: '',
      contractId: '',
      projectId: '',
      zlfName: '',
      ot: [],
      todoList: [],
      newTodoList: [],
      receiveData: [],
      filesName: [],
      refundData: [],
      paymentData: [],
      upComeData: [], //代办事项
      upCome: '',
      imgData: [],
      receiveRefund: {
        expense_name: '租金',
        amount: '0',
        memo: '',
        type: 'R'
      }, //应收租金
      refundRent: {
        expense_name: '租金',
        amount: '0',
        memo: '',
        type: 'R'
      }, //应退租金
      deposit: '', //押金/保证金
      checkStatus: '',
      checkBoxList: [],
      charge: {
        expense_name: '',
        amount: '',
        memo: '',
        type: 'T',
      },
      payment: {
        expense_name: '',
        amount: '',
        memo: '',
        type: 'T'
      },
      sum: {
        paymentSum: 0,
        chargeSum: 0
      },
      matchData: [], // 模糊匹配的费项
      contractExpense: [], // 与合同相关的费项
      nowIndex: -100,
      showCharge: false,
      showPayment: false,
      showUpCome: false,
      uploadBtn: true,
      wfMoney: 0,
      yfMoney: 0,
      timeDate: false,
      isShowSubmitConfirm: false,
      withdrawDate: '', // 退租时间
      delFlag: false,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: true,
      wpOpenFlag: true,
      stOpenFlag: true,
      validWithdraw: null,
      //20190705
      flag: false,
      ktflag: true,
      flowtype: '',
      expenditureList: [],
      regExpenditureList: [],
      progress: '',
      fileList: [],
      payData:[],
      needRefund:'',
      needReceive:'',
      totalD:'',
      showFlag:false,
      totalArr:[],
      allFlag:true
      }
    },
    filters: {
      formatNum: function (item) {
        if (item == '--') return '--'
        return hlNumberUtil.formatNum(item)
      },
      formatDate: function (time) {
        if (time === undefined) {
          return '--'
        }
        var date = new Date(time)
        return hlDateUtil.formatUTCDate(date, 'yyyy-MM-dd')
      },
    },
    methods: {
      // 整理提交data数据
      setData() {
        this.data.alteration_settle_ups = '#'

        this.data.alteration_bill = {
          begin_date: this.getContractIndex.effective_date,
          end_date: this.getContractIndex.effective_date,
          payment_deadline_date: this.getContractIndex.effective_date,
          expense_list: []
        }

        let arr = [...this.receiveData, ...this.refundData]
        arr.map(item => {
          this.data.alteration_bill.expense_list.push({
            expense_id: item.expense_id,
            expense_name: item.name,
            expense_type: item.type,
            expense_flow_type: item.flowtype,
            expense_late_fee: '#',
            custom_period: '#',
            units_code: '#',
            amount_reveice: Number(item.amount).toFixed(2),
            memo: item.memo || '#'
          })
        })
        this.data.alteration_settle_ups = JSON.stringify(this.data.alteration_settle_ups)
        this.data.alteration_bill = JSON.stringify(this.data.alteration_bill)
      },
      // 保存
      save() {
        this.setData();
        if (this.mode == 'edit') {
          this.data.alter_id = this.getContractIndex.alter_id
          hlhttp.put({
            url: 'contract_history',
            data: this.data,
            success: (res) => {
              hl.toast('编辑成功') 
              this.clearStorage()
              hlUrlUtil.goTo('contractUpdateList')
            }
          })
        } else {
          hlhttp.post({
            url: 'contract_history',
            data: this.data,
            success: (res) => {
              hl.toast('保存成功')
              this.clearStorage()
              hlUrlUtil.goTo('contractUpdateList')
            }
          })
        }
      },
      // 获取部分账单
      getClashBills() {

        hlhttp.get({
          url: 'contracts/clash_bills',
          data: {
            contract_id: this.id,
            end_date: this.getContractIndex.effective_date
          },
          success: (res) => {
            this.allFlag = res.conflictBills[0].withdrawBeginDate?true:false
            if(!this.allFlag){
              this.conflictBills = []
              return
            }
            this.conflictBills = res.conflictBills
            this.withdrawRefundExpenses = res.withdrawRefundExpenses
            let ex = res.conflictBills[0].expenses[0].withdrawAmount
            let moneyCha = (ex.amountPayed*1 + ex.derateExpense*1 + ex.carryOverAmount*1 - ex.amountReceive*1).toFixed(2)
            if(moneyCha<0){
              // 说明不展示应收金额
              this.needReceive = moneyCha*(-1)
              // 应收部分显示数据
              this.receiveData.push(
                {
                  expense_id: this.conflictBills[0].expenses[0].expenseId,
                  expense_name: "固定租金",
                  amount: this.needReceive,
                  flowtype:'RC',
                  memo: '账单：'+ this.conflictBills[0].billNo,
                  name:'固定租金',
                  disabled:true,
                  type: this.withdrawRefundExpenses[0].type
                }
              )
            }
            else if(moneyCha>0){
              // 说明展示应退金额
              this.needRefund = moneyCha
              // 应退部分展示数据
              this.refundData.push(
                {
                  expense_id: this.conflictBills[0].expenses[0].expenseId,
                  expense_name: "固定租金退款",
                  amount: this.needRefund,
                  flowtype:'RF',
                  memo: '账单：'+this.conflictBills[0].billNo,
                  disabled:true,
                  type: this.withdrawRefundExpenses[0].type
                }
              )
            }
          }
        })
      },
      // 提交审核
      submit() {
        this.setData();
        hlhttp.put({
          url: 'contract_history/_submit',
          data: this.data,
          success: (res) => {
            hl.toast('提交审核成功')
            this.clearStorage()
            hlUrlUtil.goTo('contractUpdateList')
          }
        })
      },
      // 清缓存
      clearStorage() {
        var keyArr = [
          'CHANGE_CONTRACT_INDEX',
          'CHANGE_CONTRACT_GROUPLOPS',
          'CHANGE_CONTRACT_CONTRAST',
          'CHANGE_CONTRACT_002',
          'pageIndex',
          'CONTRACT_DETAIL'
        ]
        hlStorage.ssClearMultipleKey(keyArr)
      },
      // 生成明细
      createDetail() {
        if(!this.allFlag){
          this.totalD = 0
          this.showFlag = true
          this.totalArr = []
          return
        }
        let toa = []
        this.receiveData.forEach(item=>{
          toa.push(Number(item.amount))
        })
        let tob = []
        this.refundData.forEach(item=>{
          tob.push(Number(item.amount))
        })
        let m = 0
        if(toa.length>0){
           m = toa.reduce((a,b)=> (a+b).toFixed(2))
        }
        let n = 0
        if(tob.length>0){
           n = tob.reduce((a,b)=>(a+b).toFixed(2))
        }
        this.totalD = m -n
        this.totalArr = [...this.receiveData,...this.refundData]
        this.showFlag = true
      },
      
      // 前往账单详情
      goToBill(item) {
        hlUrlUtil.goTo('billDetail', { 'id': item.billId, 'aid': this.id, 'page': 'billList' }, true)
      },
      // 上一步
      previous() {
        window.changePage.pageIndex--
      },

      // 添加费用
      pushReceive: function (val) {
        if (this.chargeData.length === 1) {
          return false
        }
        this.flag = true
        this.flowtype = val
      },
      pushRefund: function (val) {
        if (this.paymentData.length === 1) {
          return false
        }
        this.flag = true
        this.flowtype = val
      },
      //删除当前选中行
      del: function (_data, dataIndex) {
        _data.splice(dataIndex, 1);
      },
      queryExpenditure(ops) {
        console.log(ops);
        this.showFlag = false
        this.flag = false
        if (!ops.name) return
        ops.expense_name = ops.name
        ops.mac_flag = 'Y'
        ops.isShow = true
        ops.flowtype = this.flowtype
        if (this.flowtype == 'RC') {
          this.receiveData.push(ops)
        } else {
          this.refundData.push(ops)
        }
      },
    },
    computed: {
      chargeTotal: function () {
        var sum = 0;
        for (var i = 0; i < this.receiveData.length; i++) {
          sum += Number(this.receiveData[i].amount);
        }
        this.sum.chargeSum = sum.toFixed(2);
        return sum.toFixed(2);
      },
      paymentTotal: function () {
        var sum = 0;
        for (var i = 0; i < this.refundData.length; i++) {
          sum += Number(this.refundData[i].amount);
        }
        this.sum.paymentSum = sum.toFixed(2);
        return sum.toFixed(2);
      },
      total: function () {
        var all = this.sum.chargeSum - this.sum.paymentSum;
        if (all < 0) {
          return hlNumberUtil.formatNum(Math.abs(all)) + '元（应退）'
        } else if (all > 0) {
          return hlNumberUtil.formatNum(all) + '元（应付）'
        } else {
          return hlNumberUtil.formatNum(all) + '元'
        }
      }
    },
    mounted() {
      this.data = JSON.parse(window.sessionStorage.getItem('CHANGE_CONTRACT_CONTRAST'))
      this.getClashBills();
    },
  })
}())